﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// add
using System.Net.Sockets;
using System.Net;
using LibTCP;

namespace TCPAsyncClient
{
    class Program
    {
        static bool mbTestSK4050 = false;
        //private static readonly Socket mSocket = new Socket(
        //    AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static Socket mSocket = new Socket(
            AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        private const int gcPORT = 9000;

        static string msFileSK50RequestBarcode;
        static string msFileSK50RequestBarcodeNotFind;

        static void Main(string[] args)
        {
            Console.Title = "Client";
            ConnectToServer();

            msFileSK50RequestBarcode = @"C:\Temp\BufferSample-SK50RequestBarcode.txt";
            msFileSK50RequestBarcodeNotFind = @"C:\Temp\BufferSample-SK50RequestBarcodeNotFind.txt";

            if (mbTestSK4050)
            {
                RequestLoopSK4050();
            }
            else
            {
                RequestLoop();
            }

            Exit();
        }
        private static void ConnectToServer()
        {
            int iAttempts = 0;

            while (!mSocket.Connected)
            {
                try
                {
                    iAttempts++;
                    Console.WriteLine("Connection attempt " + iAttempts);
                    mSocket.Connect(IPAddress.Loopback, gcPORT);
                }
                catch (SocketException)
                {
                    Console.Clear();
                }
            }

            Console.Clear();
            Console.WriteLine("Connected");
        }

        private static void RequestLoopSK4050()
        {
            Console.WriteLine(@"SendRequestBarcode from sk40/50.");

            SendRequestSK4050();
            ReceiveResponse();
        }
        private static void RequestLoop()
        {
            Console.WriteLine(@"<Type ""exit"" to properly disconnect client>");

            while (true)
            {
                SendRequest();
                ReceiveResponse();
            }
        }

        /// <summary>
        /// Close socket and exit app
        /// </summary>
        private static void Exit()
        {
            SendString("exit"); // Tell the server we re exiting
            mSocket.Shutdown(SocketShutdown.Both);
            mSocket.Close();
            Environment.Exit(0);
        }

        private static void SendRequestSK4050()
        {
            byte[] baCmd;

            // testing
            Console.Write("Send a request sk40 50:");
            if (CCommon.LoadBuffer(msFileSK50RequestBarcode, out baCmd))
                SendBuffer(baCmd);
        }
        private static void SendRequest()
        {
            string sRequest;
            //string sLower;
            string sCmd;
            byte[] baCmd;

            // testing
            //request = "get time";
            Console.Write("Send a request: (exit or get time)");
            sRequest = Console.ReadLine();
            sCmd = sRequest.ToLower();
            if (sCmd == "request")
            {
                if (CCommon.LoadBuffer(msFileSK50RequestBarcode, out baCmd))
                    SendBuffer(baCmd);
            }
            else if (sCmd == "requestnotfind")
            {
                if (CCommon.LoadBuffer(msFileSK50RequestBarcodeNotFind, out baCmd))
                    SendBuffer(baCmd);
            }
            else
            {
                sRequest = sCmd;
                SendString(sRequest);
            }
            if (sCmd == "exit")
            {
                Exit();
            }
        }

        /// <summary>
        /// Sends a string to the server with ASCII encoding
        /// </summary>
        private static void SendString(string text)
        {
            byte[] baSend = Encoding.ASCII.GetBytes(text);
            mSocket.Send(baSend, 0, baSend.Length, SocketFlags.None);
        }
        private static void SendBuffer(byte[] baSend)
        {
            mSocket.Send(baSend, 0, baSend.Length, SocketFlags.None);
        }

        private static void ReceiveResponse()
        {
            // todo: Wait for select!


            //byte[] baBuffer = new byte[2048];
            byte[] baBuffer = new byte[512000];

            int iReceived = mSocket.Receive(baBuffer, SocketFlags.None);
            if (iReceived == 0)
            {
                Console.WriteLine("Nothing in ReceiveResponse().");
                return;
            }

            CCommon.SaveBuffer(@"C:\temp\Buffer-Client-Receive.txt", baBuffer, 0, iReceived);

            byte[] baReceived = new byte[iReceived];
            Array.Copy(baBuffer, baReceived, iReceived);
            string text = Encoding.ASCII.GetString(baReceived);
            Console.WriteLine(text);
        
        }
    }
}
